using UnityEngine;
using System.Collections.Generic;

public class BulletSpawner : MonoBehaviour
{
    [Header("射击设置")]
    public GameObject bulletPrefab;
    public GameObject[] upgradedBulletPrefabs; // 升级子弹预制体数组
    public Transform firePoint;
    public float fireRate = 0.2f; // 射击间隔
    public float bulletSpeed = 15f;
    public int bulletDamage = 1;
    
    [Header("子弹升级")]
    public int currentBulletLevel = 0; // 当前子弹等级
    public int maxBulletLevel = 3; // 最大子弹等级

    [Header("射击模式")]
    public ShootingMode shootingMode = ShootingMode.Single;
    public int burstCount = 3; // 连发数量
    public float burstDelay = 0.05f; // 连发间隔
    public float spreadAngle = 15f; // 散射角度

    [Header("输入设置")]
    public KeyCode fireKey = KeyCode.Space;
    public bool autoFire = true; // 自动射击

    [Header("对象池设置")]
    public bool useObjectPooling = false;
    public int poolSize = 50;

    [Header("调试设置")]
    public bool showDebugInfo = true;

    private float nextFireTime;
    private int currentBurstCount;
    private float nextBurstTime;
    private bool isBursting;

    // 对象池相关
    private Queue<GameObject> bulletPool;
    private Transform bulletContainer;

    public enum ShootingMode
    {
        Single,    // 单发
        Burst,     // 连发
        Spread     // 散射
    }

    void Start()
    {
        // 如果没有设置发射点，创建一个
        if (firePoint == null)
        {
            // 尝试找到玩家对象
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            if (player != null)
            {
                // 如果找到玩家，将发射点设置在玩家位置上方
                GameObject firePointObj = new GameObject("FirePoint");
                firePointObj.transform.SetParent(player.transform);
                firePointObj.transform.localPosition = Vector3.up * 0.5f;
                firePoint = firePointObj.transform;
                Debug.Log("发射点已设置到玩家位置");
            }
            else
            {
                // 如果没找到玩家，使用当前对象
                GameObject firePointObj = new GameObject("FirePoint");
                firePointObj.transform.SetParent(transform);
                firePointObj.transform.localPosition = Vector3.up * 0.5f;
                firePoint = firePointObj.transform;
                // 未找到玩家时，禁止自动射击，避免在场景中心误射
                autoFire = false;
                Debug.LogWarning("未找到带有 Player 标签的对象，已将发射点设置到 BulletSpawner 且禁用自动射击。请确保将 BulletSpawner 挂在玩家对象上。");
            }
        }

        // 如果没有设置子弹预制体，创建一个简单的
        if (bulletPrefab == null)
        {
            CreateDefaultBulletPrefab();
        }
        
        // 初始化升级子弹预制体
        InitializeUpgradedBullets();

        // 初始化对象池
        InitializeObjectPool();

        Debug.Log("弹幕发射器已初始化");
    }

    void Update()
    {
        HandleInput();
        HandleBurstFire();

        if (showDebugInfo)
        {
            Debug.Log($"射击模式: {shootingMode}, 下次射击时间: {nextFireTime - Time.time}");
        }
    }

    void HandleInput()
    {
        // 仅当发射点隶属玩家时允许射击
        if (!IsAttachedToPlayer())
        {
            return;
        }
        bool shouldFire = false;

        if (autoFire)
        {
            shouldFire = true;
        }
        else
        {
            shouldFire = Input.GetKey(fireKey);
        }

        if (shouldFire && CanFire())
        {
            Fire();
        }
    }

    void HandleBurstFire()
    {
        // 若当前不隶属玩家，则停止连发流程
        if (!IsAttachedToPlayer())
        {
            isBursting = false;
            return;
        }

        if (isBursting && Time.time >= nextBurstTime)
        {
            FireSingleBullet(Vector2.up);
            currentBurstCount++;

            if (currentBurstCount >= burstCount)
            {
                isBursting = false;
                nextFireTime = Time.time + fireRate;
            }
            else
            {
                nextBurstTime = Time.time + burstDelay;
            }
        }
    }

    bool CanFire()
    {
        return Time.time >= nextFireTime && !isBursting;
    }

    void Fire()
    {
        switch (shootingMode)
        {
            case ShootingMode.Single:
                FireSingle();
                break;
            case ShootingMode.Burst:
                FireBurst();
                break;
            case ShootingMode.Spread:
                FireSpread();
                break;
        }
    }

    void FireSingle()
    {
        FireSingleBullet(Vector2.up);
        nextFireTime = Time.time + fireRate;
    }

    void FireBurst()
    {
        isBursting = true;
        currentBurstCount = 0;
        nextBurstTime = Time.time;
    }

    void FireSpread()
    {
        int bulletCount = 3;
        float angleStep = spreadAngle / (bulletCount - 1);
        float startAngle = -spreadAngle / 2f;

        for (int i = 0; i < bulletCount; i++)
        {
            float angle = startAngle + (angleStep * i);
            Vector2 direction = Quaternion.Euler(0, 0, angle) * Vector2.up;
            FireSingleBullet(direction);
        }

        nextFireTime = Time.time + fireRate;
    }

    public GameObject GetPooledBullet()
    {
        GameObject currentPrefab = GetCurrentBulletPrefab();
        
        if (!useObjectPooling)
        {
            return Instantiate(currentPrefab, firePoint.position, Quaternion.identity);
        }

        if (bulletPool.Count > 0)
        {
            GameObject bullet = bulletPool.Dequeue();
            bullet.transform.position = firePoint.position;
            bullet.transform.rotation = Quaternion.identity;
            bullet.SetActive(true);
            return bullet;
        }

        // 如果池中没有可用对象，创建新的
        return Instantiate(currentPrefab, firePoint.position, Quaternion.identity, bulletContainer);
    }

    void FireSingleBullet(Vector2 direction)
    {
        if (bulletPrefab == null || firePoint == null) return;

        GameObject bullet = GetPooledBullet();

        BulletController bulletController = bullet.GetComponent<BulletController>();
        if (bulletController != null)
        {
            bulletController.SetDirection(direction);
            bulletController.SetSpeed(bulletSpeed);
            bulletController.SetBulletType(BulletController.BulletType.Player);
            bulletController.damage = Mathf.Max(1, bulletDamage);

            // 设置对象池回调
            bulletController.SetBulletSpawner(this);
        }

        // 设置子弹的父对象（用于组织层级）
        if (!useObjectPooling)
        {
            bullet.transform.SetParent(GameObject.Find("Bullets")?.transform);
        }

        if (showDebugInfo)
        {
            Debug.Log($"发射子弹: 位置={firePoint.position}, 方向={direction}");
        }
    }

    // 判断发射点是否挂在玩家对象（含任意祖先为 Player 标签）
    bool IsAttachedToPlayer()
    {
        if (firePoint == null) return false;
        Transform t = firePoint;
        while (t != null)
        {
            if (t.CompareTag("Player")) return true;
            t = t.parent;
        }
        return false;
    }

    void CreateDefaultBulletPrefab()
    {
        // 创建默认玩家子弹预制体
        GameObject bullet = new GameObject("DefaultPlayerBullet");

        // 添加精灵渲染器
        SpriteRenderer sr = bullet.AddComponent<SpriteRenderer>();
        sr.sprite = CreateBulletSprite();
        sr.color = Color.cyan;

        // 添加碰撞器
        CircleCollider2D collider = bullet.AddComponent<CircleCollider2D>();
        collider.radius = 0.1f;
        collider.isTrigger = true;

        // 添加刚体
        Rigidbody2D rb = bullet.AddComponent<Rigidbody2D>();
        rb.gravityScale = 0f;

        // 添加子弹控制器
        bullet.AddComponent<BulletController>();

        // 设置标签
        bullet.tag = "PlayerBullet";

        bulletPrefab = bullet;

        Debug.Log("已创建默认玩家子弹预制体");
    }

    Sprite CreateBulletSprite()
    {
        // 创建简单的子弹精灵
        Texture2D texture = new Texture2D(16, 16);
        Color[] pixels = new Color[16 * 16];

        for (int i = 0; i < pixels.Length; i++)
        {
            int x = i % 16;
            int y = i / 16;
            float distance = Vector2.Distance(new Vector2(x, y), new Vector2(8, 8));

            if (distance <= 6)
            {
                pixels[i] = Color.white;
            }
            else
            {
                pixels[i] = Color.clear;
            }
        }

        texture.SetPixels(pixels);
        texture.Apply();

        return Sprite.Create(texture, new Rect(0, 0, 16, 16), new Vector2(0.5f, 0.5f));
    }

    // 公共方法：设置射击模式
    public void SetShootingMode(ShootingMode mode)
    {
        ShootingMode oldMode = shootingMode;
        shootingMode = mode;
        Debug.Log($"[BulletSpawner] 射击模式已从 {oldMode} 切换为: {mode}");
    }

    // 公共方法：设置射击频率
    public void SetFireRate(float rate)
    {
        fireRate = Mathf.Max(0.05f, rate); // 最小间隔0.05秒
        Debug.Log($"射击频率已设置为: {fireRate}");
    }

    // 公共方法：设置子弹速度
    public void SetBulletSpeed(float speed)
    {
        bulletSpeed = Mathf.Max(1f, speed); // 最小速度1
        Debug.Log($"子弹速度已设置为: {bulletSpeed}");
    }
    
    // 公共方法：升级子弹
    public void UpgradeBullet()
    {
        if (currentBulletLevel < maxBulletLevel)
        {
            currentBulletLevel++;
            Debug.Log($"子弹已升级到等级: {currentBulletLevel}");
        }
        else
        {
            Debug.Log("子弹已达到最高等级");
        }
    }
    
    // 公共方法：降级子弹
    public void DegradeBulletLevel()
    {
        if (currentBulletLevel > 0)
        {
            currentBulletLevel--;
            Debug.Log($"子弹等级回退为: {currentBulletLevel}");
        }
        else
        {
            Debug.Log("子弹已在基础等级，无法继续回退");
        }
    }
    
    // 获取当前子弹预制体
    GameObject GetCurrentBulletPrefab()
    {
        if (currentBulletLevel == 0 || upgradedBulletPrefabs == null || upgradedBulletPrefabs.Length == 0)
        {
            return bulletPrefab;
        }
        
        int index = Mathf.Min(currentBulletLevel - 1, upgradedBulletPrefabs.Length - 1);
        return upgradedBulletPrefabs[index] != null ? upgradedBulletPrefabs[index] : bulletPrefab;
    }

    void OnDrawGizmos()
    {
        if (firePoint != null)
        {
            // 绘制发射点
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(firePoint.position, 0.2f);

            // 绘制射击方向
            Gizmos.color = Color.green;
            Gizmos.DrawLine(firePoint.position, firePoint.position + Vector3.up * 2f);

            // 绘制散射角度
            if (shootingMode == ShootingMode.Spread)
            {
                Gizmos.color = Color.red;
                Vector3 leftDirection = Quaternion.Euler(0, 0, -spreadAngle / 2f) * Vector3.up;
                Vector3 rightDirection = Quaternion.Euler(0, 0, spreadAngle / 2f) * Vector3.up;

                Gizmos.DrawLine(firePoint.position, firePoint.position + leftDirection * 2f);
                Gizmos.DrawLine(firePoint.position, firePoint.position + rightDirection * 2f);
            }
        }
    }

    // 对象池相关方法
    void InitializeObjectPool()
    {
        if (!useObjectPooling) return;

        bulletPool = new Queue<GameObject>();

        // 创建子弹容器
        GameObject container = GameObject.Find("Bullets");
        if (container == null)
        {
            container = new GameObject("Bullets");
        }
        bulletContainer = container.transform;

        // 预创建子弹对象
        for (int i = 0; i < poolSize; i++)
        {
            GameObject bullet = Instantiate(bulletPrefab, bulletContainer);
            bullet.SetActive(false);
            bulletPool.Enqueue(bullet);
        }

        Debug.Log($"子弹对象池已初始化，池大小: {poolSize}");
    }


    public void ReturnBulletToPool(GameObject bullet)
    {
        if (!useObjectPooling)
        {
            Destroy(bullet);
            return;
        }

        bullet.SetActive(false);
        bullet.transform.SetParent(bulletContainer);
        bulletPool.Enqueue(bullet);
    }

    public void EnableObjectPooling(bool enable)
    {
        useObjectPooling = enable;
        if (enable && bulletPool == null)
        {
            InitializeObjectPool();
        }
        Debug.Log($"子弹对象池已{(enable ? "启用" : "禁用")}");
    }
    
    void InitializeUpgradedBullets()
    {
        // 如果没有设置升级子弹预制体数组，尝试从Resources加载
        if (upgradedBulletPrefabs == null || upgradedBulletPrefabs.Length == 0)
        {
            upgradedBulletPrefabs = new GameObject[maxBulletLevel];
            
            // 加载升级子弹预制体
            GameObject upgradedBullet = Resources.Load<GameObject>("Prefabs/UpgradedBullet");
            if (upgradedBullet != null)
            {
                upgradedBulletPrefabs[0] = upgradedBullet;
                Debug.Log("已加载升级子弹预制体");
            }
            else
            {
                Debug.LogWarning("未找到升级子弹预制体，将使用默认子弹");
            }
        }
    }
}